import {
  getOrderDetail, cancelOrder, buy, confirmDelivery,
  confirmReturn, payOrder, renewal, getSettle, getSignInfo
} from '../../services/order';

Page({
  data: {
    modalOpened: false,
    modalOpened2: false,
    returnExpressNo: '',
    returnExpressName: '',
    lostMoney: '',
    damageMoney: '',
    violateMoney: '',
    totalMoney: '',
    settleRemark: '',

    globalData: getApp().globalData,
    text: '11111',
    orderId: '',
    orderInfo: {}
  },
  onShow() {
    my.setNavigationBar({
      title: '订单详情',
      backgroundColor: '#4BA3F9'
    })
    this.getOrderDetail();
  },
  onLoad(event) {
    this.setData({ orderId: event.orderId })
  },
  agreementClick() {
    getSignInfo({ orderId: this.data.orderId }).then(res => {
      if (res.code == "000000") {
        let url = res.data.accountId
        if(res.data.isSign == 0){
          let start = url.indexOf(`?appId=`);
          let end = url.indexOf(`&page=`);
          let appId = url.substring(start+7,end);
          let path = url.substring(end+6,url.length).replace("&query=","?");
          console.log(url);
          console.log(appId);
          console.log(path);
         my.navigateToMiniProgram({
           appId: appId,
           path: path,
           success: (res) => {
           },
           fail: (res) => {
           }
           });
        } else if(res.data.isSign == 1) {
          let url = res.data.accountId
          console.log(url);
          //todo pdf地址

          my.downloadFile({
            url: url,
            success ({ apFilePath }) {
              my.hideLoading();
              my.openDocument({
                filePath: apFilePath,
                fileType: 'pdf',
                success: (res) => {
                  console.log(res);
                },
                fail: (res) => {
                  console.log(res);
                }
              })
            }
          })
        }
      }
    })
  },
  submit() {
    my.showToast({
      type: 'success',
      content: '支付成功',
    })

    my.startPullDownRefresh()
  },
  getOrderDetail() {
    getOrderDetail({ orderId: this.data.orderId }).then(res => {
      if (res.code == "000000") {
        let isCanQueryShop = true
        let orderStatusName = ''
        let isCanCancel = false//可取消
        let isCanPay = false//可支付
        let isCanLookDelivery = false//可查看物流
        let isCanBack = false //可以确认归还
        let isCanBackOrderStatus = false //可以确认归还主状态
        let isCanBackSubstatus = false //可以确认归还子状态
        let isCanconfirmDelivery = false //可以确认收货
        let isCanLookSettle = false //可以查看结算单
        let isCanBuyOut = false //可以买断
        let isCanRelet = false //可以续租
        let isCanLookStage = false//查看分期账单
        switch (res.data.orderStatus) {
          case 'USER_CANCELED_CLOSED':
            orderStatusName = '用户取消'
            isCanLookStage = true
            isCanQueryShop = false
            break;
          case 'BUSINESS_CANCELED_CLOSED':
            isCanQueryShop = false
            orderStatusName = '商家取消'
            break;
          case 'ALREADY_FREEZE':
            orderStatusName = '金额已冻结'
            isCanQueryShop = false
            isCanCancel = true
            isCanPay = true
            isCanLookStage = true
            break;
          case 'WAITING_PAYMENT':
            isCanQueryShop = false
            orderStatusName = '待付款'
            isCanCancel = true
            isCanPay = true
            isCanLookStage = true
            break;
          case 'USER_OVERTIME_PAYMENT_CLOSED':
            isCanQueryShop = false
            orderStatusName = '超时支付关闭'
            break;
          case 'DELIVERY_OVERTIME_CLOSED':
            isCanQueryShop = false
            orderStatusName = '超时发货关闭'
            break;
          case 'WAITING_BUSINESS_DELIVERY':
            orderStatusName = '待发货'
            isCanCancel = true
            isCanLookStage = true
            break;
          case 'WAITING_USER_RECEIVE_CONFIRM':
            orderStatusName = '待收货'
            isCanconfirmDelivery = true
            isCanLookStage = true
            break;
          case 'WAITING_GIVE_BACK':
            orderStatusName = '租用中'
            isCanBack = true;
            isCanBuyOut = true;
            isCanRelet = true;
            isCanLookStage = true
            break;
          case 'WAITING_SETTLEMENT':
            orderStatusName = '待结算'
            isCanBuyOut = true
            isCanBackOrderStatus = true;
            break;
          case 'WAITING_SETTLEMENT_PAYMENT':
            orderStatusName = '待结算付款'
            isCanLookSettle = true
            break;
          case 'ORDER_FINISH':
            orderStatusName = '已完成'
            isCanLookStage = true
            break;
          case 'RENEWAL_SUCCESS':
            orderStatusName = '续租成功'
            isCanBack = true
            isCanBuyOut = true
            isCanRelet = true
            isCanLookStage = true
            break;
        }
        if (res.data.subStatus == 'WAITING_UPLOAD_RETURNING_INFO') {
          isCanBackSubstatus = true;
        }
        if (isCanBackOrderStatus && isCanBackSubstatus) {
          isCanBack = true;
        }
        res.data.isCanQueryShop = isCanQueryShop
        res.data.isCanCancel = isCanCancel
        res.data.isCanPay = isCanPay
        res.data.isCanLookDelivery = isCanLookDelivery
        res.data.isCanBack = isCanBack
        res.data.isCanconfirmDelivery = isCanconfirmDelivery
        res.data.isCanLookSettle = isCanLookSettle
        res.data.isCanBuyOut = isCanBuyOut
        res.data.isCanRelet = isCanRelet
        res.data.isCanLookStage = isCanLookStage
        res.data.orderStatusName = orderStatusName
        res.data.isCanCancel = isCanCancel
        res.data.isCanPay = isCanPay
        res.data.isCanLookDelivery = isCanLookDelivery
        res.data.isCanBack = isCanBack
        res.data.isCanconfirmDelivery = isCanconfirmDelivery
        res.data.isCanLookSettle = isCanLookSettle
        res.data.isCanBuyOut = isCanBuyOut
        res.data.isCanRelet = isCanRelet
        res.data.isCanLookStage = isCanLookStage
        res.data.orderStatusName = orderStatusName
        this.setData({ orderInfo: res.data })
      }
    })
  },
  handlePaste(event) {
    my.setClipboard({
      text: event.target.dataset.copy,
      success: () => {
        console.log('success')
      },
    });
  },
  toKf() {
    my.switchTab({
      url: '/pages/customer/customer',
    })
  },
  todetail(event) {
    my.navigateTo({
      url: '/pages/orderDetail/orderDetail?orderId=' + event.target.dataset.id,
    })

  },
  lookstage(event) {
    my.navigateTo({
      url: '/pages/billStages/index?orderId=' + event.target.dataset.id,
    })
  },
  cancelOrder(event) {
    my.prompt({
      title: '取消订单',
      message: '请填写取消原因',
      okButtonText: '确定',
      cancelButtonText: '取消',
      success: (result) => {
        if (result.ok) {
          if (result.inputValue.length <= 0) {
            my.showToast({
              type: 'fail',
              content: '请填写取消原因',
              duration: 2000,
            });
            return
          }
          cancelOrder({ orderId: event.target.dataset.id, cancelReason: result.inputValue }).then(res => {
            if (res.code == "000000") {
              my.showToast({
                type: 'success',
                content: '取消成功，已付款将在1个工作日内退回',
                duration: 2000,
              });
              setTimeout(() => {
                my.startPullDownRefresh()
              }, 2000);
            }
          })
        }

      },
    });
  },

  confirmDelivery(event) {
    my.prompt({
      title: '确认收货',
      message: '请输入收到设备的设备码',
      okButtonText: '确定',
      cancelButtonText: '取消',
      success: (result) => {
        if (result.ok) {
          if (result.inputValue.length <= 0) {
            my.showToast({
              type: 'fail',
              content: '请输入收到设备的设备码',
              duration: 2000,
            });
            return
          }
          confirmDelivery({ orderId: event.target.dataset.id,imei: result.inputValue }).then(res => {
            if (res.code == "000000") {
              my.startPullDownRefresh()
            }
          })
        }
      },
    });
  },
  byuout(event) {
    my.confirm({
      title: '温馨提示',
      content: '确定买断吗?',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      success: (result) => {
        if (result.confirm) {
          buy({ orderId: event.target.dataset.id }).then(res => {
            if (res.code == "000000") {
              this.onpayOrder(event.target.dataset.id, res.data)
            }
          })
        }
      },
    });
  }
  ,
  relet(event) {
    my.confirm({
      title: '温馨提示',
      content: '确定续租吗?',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      success: (result) => {
        if (result.confirm) {
          renewal({ orderId: event.target.dataset.id }).then(res => {
            if (res.code == "000000") {
              my.startPullDownRefresh()
            }
          })
        }
      },
    });
  }
  ,

  onItemInput(e) {

    this.setData({

      [e.target.dataset.field]: e.detail.value,

    });

  },
  onClear(e) {

    this.setData({

      [e.target.dataset.field]: '',

    });

  },
  openModal(event) {
    let orderId = event.target.dataset.id
    this.setData({
      modalOpened: true,
      returnExpressName: '',
      returnExpressNo: '',
      orderId: orderId
    });

  },
  onModalClose2() {
    this.setData({
      modalOpened2: false,
    });
  },
  onModalClose() {
    this.setData({
      modalOpened: false,
    });
  },
  looksettle(event) {
    getSettle({ orderId: event.target.dataset.id }).then(res => {
      if (res.code == "000000") {
        this.setData({
          modalOpened2: true,
          lostMoney: res.data.lostMoney,
          violateMoney: res.data.violateMoney,
          totalMoney: res.data.totalMoney,
          damageMoney: res.data.damageMoney,
          settleRemark: res.data.settleRemark
          ,
          orderId: event.target.dataset.id
        });
      }
    })

  }
  ,

  backorder() {
    if (this.data.returnExpressNo.length <= 0) {
      my.showToast({
        type: 'fail',
        content: '请填写快递单号',
        duration: 2000,
      });
      return
    }
    if (this.data.returnExpressName.length <= 0) {
      my.showToast({
        type: 'fail',
        content: '请填写快递名称',
        duration: 2000,
      });
      return
    }

    confirmReturn({
      orderId: this.data.orderId,
      returnExpressName: this.data.returnExpressName,
      returnExpressNo: this.data.returnExpressNo
    }).then(res => {
      if (res.code == 0) {
        this.onModalClose()
        my.startPullDownRefresh()
      }
    })
  },

  onpayOrder(orderID, data) {
    if (data.payType == 0) {
      my.showToast({
        type: 'fail',
        content: data.payData,
        duration: 2000,
      });
      return
    } else if (data.payType == 1) {
      my.tradePay({
        tradeNO: data.payData,
        success: function (res) {
          if (res.resultCode == 9000) {
            my.startPullDownRefresh()
            my.showToast({
              type: 'success',
              content: '支付成功',
              duration: 2000,
            })
          } else {
            my.showToast({
              type: 'fail',
              content: '支付失败',
              duration: 2000,
            })
          }
        },
        fail: function (res) {
          console.log(res)
        },
      })
    }
  },

  payOrder(event) {
    let orderID = event.target.dataset.id
    payOrder({
      orderId: orderID
    }).then(res2 => {
      if (res2.code == "000000") {
        this.onpayOrder(orderID, res2.data)
      }
    })
  },
  payorder2(event) {

    payOrder({
      orderId: this.data.orderId
    }).then(res2 => {
      if (res2.code == "000000") {
        this.onpayOrder(this.data.orderId, res2.data)
        this.onModalClose2()
      }
    })
  },
  getNearShopList() {
    my.navigateTo({
      url: "/pages/shop/shop?orderId=" + this.data.orderId
    })
  }
});
